package com.google.code.jholidays.parsers;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.code.jholidays.events.DependentEvent;
import com.google.code.jholidays.events.DependentEventFactory;
import com.google.code.jholidays.events.parameters.Offset;

/**
 * Represents parser which can extract {@link Offset} from {@link String}
 * expression. This parser is used by {@link DependentEventFactory} in the
 * process of construction of {@link DependentEvent} instances.
 * 
 * @author tillias
 * @see DependentEventFactory
 * @see DependentEvent
 * @see Offset
 * 
 */
public class OffsetParser {

    /**
     * Parses given string and returns {@link Offset}
     * 
     * @param expression
     *            String which possible contains {@link Offset}
     * @return {@link Offset} if succeeded, null otherwise
     */
    public Offset parseOffset(String expression) {
	Offset result = null;

	try {
	    Matcher matcher = pattern.matcher(expression);

	    if (matcher.matches()) {
		if (matcher.groupCount() == groupsCount) {

		    String daysCountStr = matcher.group(1);

		    // XXX: replace '+' if present in expression, since int
		    // doesn't parse it
		    int daysCount = Integer.parseInt(daysCountStr.replace('+',
			    '0'));
		    result = new Offset(daysCount);
		}
	    }
	} catch (Exception e) {
	    // nothing todo here
	}

	return result;
    }

    /**
     * Checks whether given string represents {@link Offset}
     * 
     * @param expression
     *            String representation of offset
     * @return True if input string represents {@link Offset}, false otherwise
     */
    public boolean matches(String expression) {
	return pattern.matcher(expression).matches();
    }

    private final static Pattern pattern = Pattern
	    .compile("(-{0,1}\\d+|\\+{0,1}\\d+)");
    private final static int groupsCount = 1;
}
